﻿/* **************************************************************************
 *
 * Copyright 2007-2010 Jeff Hardy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * *************************************************************************/

using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using IronPython.Runtime;

namespace NWSGI
{
    [PythonType]
    public class WsgiInputStream
    {
        private Stream input;
        private int contentLength;

        public WsgiInputStream(Stream input, int contentLength)
        {
            this.input = input;
            this.contentLength = contentLength;
        }

        public string read()
        {
            byte[] data = new byte[64 * 1024];
            StringBuilder result = new StringBuilder();

            int len;
            while((len = input.Read(data, 0, data.Length)) > 0)
            {
                result.Append(Wsgi.Latin1.GetString(data, 0, len));
            }

            return result.ToString();
        }

        public string read(int size)
        {
            if(size < 0)
                return read();

            if(size == 0)
                return "";

            byte[] data = new byte[size];
            int len = input.Read(data, 0, data.Length);

            return len == 0 ? "" : Wsgi.Latin1.GetString(data, 0, len);
        }

        public string readline()
        {
            List<byte> data = new List<byte>();

            while(true)
            {
                int b = input.ReadByte();
                if(b < 0)       // We've reached EOF
                    break;
                
                data.Add((byte)b);

                if(b == 0x0A)   // we've reached a new line (LF) character
                    break;
            }

            return data.Count > 0 ? Wsgi.Latin1.GetString(data.ToArray()) : "";
        }

        public List readlines([DefaultParameterValue(0)]int hint)
        {
            List result = new List();
            
            string line;
            while(!string.IsNullOrEmpty(line = readline()))
                result.Add(result);

            return result;
        }

        public WsgiInputStream __iter__()
        {
            return this;
        }

        public string next()
        {
            return readline();
        }
    }
}
